<template>
  <div class="vote">
    <div data-v-539452e0 aria-label="Breadcrumb" role="navigation" class="el-breadcrumb">
      <span data-v-539452e0 class="el-breadcrumb__item">
        <span role="link" class="el-breadcrumb__inner is-link">小区管理</span>
        <span role="presentation" class="el-breadcrumb__separator">/</span>
      </span>

      <span data-v-539452e0 class="el-breadcrumb__item" aria-current="page">
        <span
          role="link"
          @click="backList"
          :class="{ 'is-link': tableFlag!=1 }"
          class="el-breadcrumb__inner"
        >投票议事</span>
        <span role="presentation" class="el-breadcrumb__separator">/</span>
      </span>
      <span data-v-539452e0 class="el-breadcrumb__item" aria-current="page" v-if="tableFlag==2">
        <span role="link" class="el-breadcrumb__inner">新增投票</span>
        <span role="presentation" class="el-breadcrumb__separator">/</span>
      </span>
      <span data-v-539452e0 class="el-breadcrumb__item" aria-current="page" v-if="tableFlag==4">
        <span role="link" class="el-breadcrumb__inner">投票详情</span>
        <span role="presentation" class="el-breadcrumb__separator">/</span>
      </span>
      <span data-v-539452e0 class="el-breadcrumb__item" aria-current="page" v-if="tableFlag==3">
        <span role="link" class="el-breadcrumb__inner">投票统计</span>
        <span role="presentation" class="el-breadcrumb__separator">/</span>
      </span>
    </div>

    <section class="section-content">
      <el-main class="content-wrapper">
        <section v-if="tableFlag==1">
          <el-row class="my-margin-top-20" :gutter="4">
            <el-col :span="2" v-if="tableFlag==1" style="min-width:120px;">
              <el-button type="primary" size="small" @click="addAnn">新增投票</el-button>
            </el-col>
            <el-col :span="4" v-if="tableFlag==1">
              <el-input
                size="small"
                placeholder="请输入关键字"
                suffix-icon="el-icon-search"
                :clearable="true"
                @clear="cleanKey"
                v-model="table.queryKey"
                @keyup.enter.native="queryKey"
              ></el-input>
            </el-col>
            <el-col :span="4" v-show="tableFlag==1" style="min-width:120px;margin-left:10px;">
              <el-select
                @change="selectChange"
                size="small"
                clearable
                v-model="table.state"
                placeholder="请选择状态"
              >
                <el-option label="新创建" value="0"></el-option>
                <el-option label="待修改" value="1"></el-option>
                <el-option label="已终止" value="2"></el-option>
                <el-option label="发布(未开始)" value="3"></el-option>
                <el-option label="发布(进行中)" value="4"></el-option>
                <el-option label="发布(已结束)" value="5"></el-option>
              </el-select>
            </el-col>
          </el-row>
          <!-- table -->
          <el-row class="my-margin-top-10" v-show="!form.isShow">
            <el-table
              :data="table.tableData"
              border
              stripe
              style="width:100%"
              size="small"
              :highlight-current-row="true"
              ref="multipleTable"
              v-loading="table.loading"
            >
              <el-table-column label="议事标题" prop="title"></el-table-column>
              <el-table-column label="状态" width="180">
                <template slot-scope="scope">
                  <span v-if="scope.row.state==0">新创建</span>
                  <span v-if="scope.row.state==1">待修改</span>
                  <span v-if="scope.row.state==2">已终止</span>
                  <span v-if="scope.row.state==3">发布(未开始)</span>
                  <span v-if="scope.row.state==4">发布(进行中)</span>
                  <span v-if="scope.row.state==5">发布(已结束)</span>
                </template>
              </el-table-column>
              <el-table-column label="投票开始时间" prop="startTime" width="180"></el-table-column>
              <el-table-column label="投票截止时间" prop="endTime" width="180"></el-table-column>
              <el-table-column label="已参与 / 总票数" prop="handCount" width="180"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <!-- 1发布 2取消 3终止 4删除 -->
                  <el-button
                    type="text"
                    @click="editStatus
                  (scope.row,1)"
                    v-if="scope.row.state==0||scope.row.state==1"
                  >发布</el-button>
                  <el-button
                    type="text"
                    @click="editStatus(scope.row,2)"
                    v-if="scope.row.state==3||scope.row.state==4"
                  >取消发布</el-button>
                  <el-button
                    type="text"
                    @click="editStatus(scope.row,3)"
                    v-if="scope.row.state==0||scope.row.state==1"
                  >终止</el-button>
                  <el-button
                    type="text"
                    @click="edit(scope.row)"
                    v-if="scope.row.state==0||scope.row.state==1"
                  >修改</el-button>
                  <el-button type="text" @click="viewDetail(scope.row)">查看详情</el-button>
                  <el-button type="text" @click="del(scope.row)" v-if="scope.row.state==2">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              class="my-margin-top-10 my-el-pagination"
              @current-change="currentChangeHandle"
              :current-page="table.currentPage"
              :page-size="table.pageSize"
              layout="total, prev, pager, next, jumper"
              :total="table.rowCount"
            ></el-pagination>
          </el-row>
        </section>
        <!-- 步骤条 -->
        <section v-if="tableFlag==2" class="setup-top">
          <el-steps :active="setupCount" align-center>
            <el-step title="投票范围" description="选择可参与投票人范围确认投票人基础数据"></el-step>
            <el-step title="基本信息" description="设置此次议事的基本信息"></el-step>
            <el-step title="附件资源" description="上传此次投票议事中涉及合同文档等资源"></el-step>
            <el-step title="选项信息" description="设置投票选项可设置单选多选"></el-step>
          </el-steps>
        </section>
        <!-- 结果统计  全部投票 -->
        <section v-if="tableFlag==3">
          <el-tabs v-model="tabName" @tab-click="tabClick">
            <el-tab-pane label="结果统计" name="result">
              <div class="result-wrapper">
                <el-collapse v-model="collapseAct" @change="collapseFn">
                  <el-collapse-item
                    v-for="(item,index) in resultData"
                    :key="index"
                    :title="item.title"
                    :name="index"
                  >
                    <el-table :data="item.options" border style="width: 100%">
                      <el-table-column prop="answerContent" label="选项">
                        <template slot-scope="scope">
                          <span>
                            {{scope.row.answerOption}}
                            {{scope.row.answerContent}}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="count" label="票数"></el-table-column>
                      <el-table-column prop="percentage" label="票数占比（%）"></el-table-column>
                      <!-- <el-table-column prop="address" label="专有部分面积（m²）"></el-table-column> -->
                    </el-table>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </el-tab-pane>
            <el-tab-pane label="全部投票" name="allVote">
              <el-row class="my-margin-top-10">
                <el-table
                  :data="allVote.tableData"
                  border
                  stripe
                  style="width:100%"
                  size="small"
                  :highlight-current-row="true"
                  ref="multipleTable"
                >
                  <el-table-column label="姓名" prop="realName"></el-table-column>
                  <el-table-column label="手机号" prop="phoneNum"></el-table-column>
                  <el-table-column label="性别" width="60">
                    <template slot-scope="scope">
                      <span v-if="scope.row.gender==1">男</span>
                      <span v-else>女</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="身份证号码" prop="idCard"></el-table-column>
                  <el-table-column label="楼栋" prop="buildNum" width="60"></el-table-column>
                  <el-table-column label="单元" prop="unitNum" width="60"></el-table-column>
                  <el-table-column label="房号" prop="houseNum" width="80"></el-table-column>
                  <el-table-column label="创建时间" prop="createTime"></el-table-column>
                  <el-table-column label="投票结果">
                    <template slot-scope="scope">
                      <el-button type="text" @click="singleDetailFn(scope.row)">查看详情</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                  class="my-margin-top-10 my-el-pagination"
                  @current-change="voteChange"
                  :current-page="allVote.currentPage"
                  :page-size="allVote.pageSize"
                  layout="total, prev, pager, next, jumper"
                  :total="allVote.rowCount"
                ></el-pagination>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </section>
        <!--详情-->

        <!--详情-->
        <section class="detail-section" v-if="tableFlag==4">
          <div class="detail-collapse">
            <el-collapse v-model="detailActive" @change="detailCollapse">
              <el-collapse-item title="投票范围" name="1">
                <div class="scope-detail">
                  <h4>{{detailScope}}</h4>
                </div>
              </el-collapse-item>
              <el-collapse-item title="基本信息" name="2">
                <div class="info-detail">
                  <div>标题：{{setup2EditForm.title}}</div>
                  <div>
                    活动时间：{{setup2EditForm.starTime[0]}} --
                    {{setup2EditForm.starTime[1]}}
                  </div>
                  <div>
                    <span class="view-region" @click="detailRegion">查看内容</span>
                  </div>
                </div>
              </el-collapse-item>
              <el-collapse-item title="附件资源" name="3">
                <div v-for="(item,index) in chooseList" :key="index" class="file-wrap">
                  {{index+1}}
                  <span v-if="item.extraType==1">(文件)</span>
                  <span v-else>(文章)</span>
                  {{item.name}}
                </div>
              </el-collapse-item>
              <el-collapse-item title="选项信息" name="4">
                <div v-for="(domain,index) in dynamicValidateForm.domains" :key="index">
                  <el-card class="box-card">
                    <div slot="header" class="clearfix">
                      <span>事项{{index+1}}</span>
                    </div>
                    <ul>
                      <li class="select-item-li">事项描述：{{domain.name}}</li>
                      <li class="select-item-li">
                        选项类型：
                        <span v-if="domain.radio==1">单选</span>
                        <span v-else>多选</span>
                      </li>
                      <li v-if="domain.radio==2" class="select-item-li">最多可选数：{{domain.selectNum}}</li>
                      <li class="detail-select-li select-item-li">
                        <div>选项描述：</div>
                        <ul>
                          <li
                            v-for="(item,childRenIndex) in domain.select"
                            :key="childRenIndex"
                          >{{item.selectZM}}.{{item.selectInput}}</li>
                        </ul>
                      </li>
                    </ul>
                  </el-card>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div class="detail-btn-wrapper">
            <el-button
              size="small"
              v-if="detailState==4||detailState==5"
              type="primary"
              @click="statistics"
            >投票统计</el-button>
            <el-button type="primary" size="small" @click="backList">返回</el-button>
          </div>
        </section>

        <div class="set-1">
          <div class="set-1-form">
            <!-- 第一步 -->
            <section v-if="setupCount==0&&tableFlag==2" class="setup-wrapper">
              <el-form ref="setup1Form" :model="setup1Form" :rules="setup1Rules">
                <el-form-item label="活动区域" prop="area">
                  <el-select v-model="setup1Form.area" placeholder="请选择活动区域">
                    <el-option
                      :label="item.communityName"
                      :value="item.communityId"
                      v-for="item in setup1Form.selectOption"
                      :key="item.communityId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </section>
            <!-- 第二步 -->
            <section v-if="setupCount==1&&tableFlag==2" class="setup-wrapper setup-wrapper-2">
              <el-form ref="setup2EditForm" :model="setup2EditForm" :rules="setup2EditRules">
                <el-form-item label="议事标题" prop="title">
                  <el-input v-model="setup2EditForm.title" style="width:400px"></el-input>
                </el-form-item>
                <el-form-item label="活动时间" prop="starTime">
                  <el-date-picker
                    v-model="setup2EditForm.starTime"
                    value-format="yyyy-MM-dd HH:mm"
                    format="yyyy-MM-dd HH:mm"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="right"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item
                  class="el-form-item_data setup-1-btn-wrap edi-wrapper"
                  label="议事详情"
                  prop="region"
                >
                  <editor
                    :value="setup2EditForm.region"
                    style="height:515px;background:#fff"
                    @input="inputFn"
                    @onEditorBlur="onEditorBlur"
                  ></editor>
                </el-form-item>
              </el-form>
            </section>

            <section v-if="setupCount==2&&tableFlag==2" class="setup-wrapper setup-wrapper-3">
              <el-button size="small" @click="setup3FetchFile">
                选择文件
                <i class="el-icon-tickets el-icon--right"></i>
              </el-button>
              <el-button size="small" @click="setup3FetchArt">
                选择文章
                <i class="el-icon-document-copy el-icon--right"></i>
              </el-button>
              <div class="list-data-wrap">
                <div v-for="(item,index) in chooseList" :key="index" class="choose-item-wrap">
                  <span class="list-item">
                    <span v-if="item.extraType==1">附件1（文件）</span>
                    <span v-else>附件2（文章）</span>
                    {{item.name}}
                  </span>
                  <span class="item-del" @click="setup3Del(index)">删除</span>
                </div>
              </div>
            </section>

            <section v-if="setupCount==3&&tableFlag==2" class="setup-wrapper-4">
              <el-form
                class="card-from"
                :model="dynamicValidateForm"
                label-width="80px"
                ref="setup4From"
              >
                <el-card
                  v-for="(domain,parentIndex) in dynamicValidateForm.domains"
                  :key="parentIndex"
                  class="box-card setup4-box-card-wrap"
                  style="margin:0 auto;margin-bottom:30px"
                >
                  <div slot="header" class="clearfix">
                    <span>事项{{parentIndex+1}}</span>
                    <i
                      v-show="domain.delItemFlag"
                      class="el-icon-delete set4-icon"
                      type="text"
                      @click="delCard(parentIndex)"
                    ></i>
                    <i
                      v-show="!domain.topFlag"
                      class="el-icon-bottom set4-icon"
                      type="text"
                      @click="botCard(parentIndex)"
                    ></i>
                    <i
                      v-show="domain.topFlag"
                      class="el-icon-top set4-icon"
                      type="text"
                      @click="topCard(parentIndex)"
                    ></i>
                  </div>
                  <div v-show="domain.topFlag" class="set4-wrap">
                    <el-form-item
                      label="事件描述"
                      :prop="'domains.' + parentIndex + '.name'"
                      :rules="[{ required: true, message: '请输入事件描述', trigger: 'blur' }]"
                    >
                      <el-input v-model="domain.name"></el-input>
                    </el-form-item>
                    <el-form-item label="选项类型" :prop="'domains.' + parentIndex + '.radio'">
                      <el-radio-group v-model="domain.radio" class="select-wrap">
                        <el-radio :label="1">单选</el-radio>
                        <el-radio :label="2">多选</el-radio>
                      </el-radio-group>
                    </el-form-item>

                    <el-form-item
                      label="可选数"
                      :prop="`domains.${parentIndex}.selectNum`"
                      v-if="domain.radio == 2"
                      :rules="[
                      { required: true, message: '请输入可选数', trigger: 'blur' },
                      { type: 'number', message: '请输入数字', trigger: 'blur' },
                      ]"
                    >
                      <el-input-number
                        style="width:250px"
                        v-model="domain.selectNum"
                        :min="1"
                        :max="domain.maxNum"
                        label="最多可选数"
                        class="max-num-input"
                      ></el-input-number>
                    </el-form-item>
                    <el-form-item label="选项描述">
                      <div
                        class="select-desc"
                        v-for="(subItem,index) in domain.select"
                        :key="index"
                      >
                        <el-form-item
                          :prop="`domains.${parentIndex}.select.${index}.selectInput`"
                          :rules="[
                      { required: true, message: '请输入描述', trigger: 'blur' },
                      ]"
                        >
                          <el-input
                            class="content-input"
                            placeholder="请输入内容"
                            v-model="subItem.selectInput"
                          >
                            <template slot="prepend">{{subItem.selectZM}}</template>
                          </el-input>
                        </el-form-item>

                        <div class="edit-btn-wrap">
                          <span v-if="subItem.addFlag" @click="addZM(parentIndex,index)">添加</span>
                          <span v-if="subItem.delFlag" @click="delZM(parentIndex,index)">删除</span>
                        </div>
                      </div>
                    </el-form-item>
                  </div>
                </el-card>
              </el-form>
              <div class="icon-wrap">
                <i class="el-icon-plus icon-add" @click="addSelect"></i>
              </div>
            </section>
            <div class="setup-1-btn-wrap" v-if="tableFlag==2">
              <el-button
                size="small"
                type="primary"
                v-if="setupCount==3"
                @click="saveVoteData('setup4From')"
              >保存</el-button>
              <el-button type="primary" size="small" v-else @click="setNext">下一步</el-button>
              <el-button size="small" v-show="setupCount!=0" @click="setBack">返回</el-button>
            </div>
          </div>
        </div>
      </el-main>
    </section>

    <!-- 选择文件 -->
    <el-dialog title="选择文件" :visible.sync="diaFileFlag" class="file-dia">
      <el-card class="box-card">
        <div
          v-for="(item,index) in fileList"
          :key="index"
          class="text item vote-card-wrap"
          @click="cRes(item)"
        >
          <div class="card-item-name">{{item.name}}</div>
          <div>
            <span class="card-item-time">{{item.createTime}}</span>
            {{item.createUserName}}
          </div>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="diaFileFlag = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择文章 -->
    <el-dialog title="选择文章" :visible.sync="diaArticleFlag" class="file-dia">
      <el-card class="box-card">
        <div
          v-for="(item,index) in artList"
          :key="index"
          class="text item vote-card-wrap"
          @click="cRes(item)"
        >
          <div class="card-item-name">{{item.title}}</div>
          <div>
            <span class="card-item-time">{{item.createTime}}</span>
            {{item.createUserName}}
          </div>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="diaArticleFlag = false">取 消</el-button>
        <el-button type="primary" @click="diaArticleFlag = false">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 延期投票 -->
    <el-dialog title="延期投票" :visible.sync="voteStatus.delayVoteFlag" width="600px" center>
      <el-form ref="voteForm" :model="voteFormDelay" label-width="100px">
        <el-form-item label="原截止日期：">
          <p>2019-04-08 16：40</p>
        </el-form-item>
        <el-form-item label="新截止时间：">
          <el-date-picker v-model="voteStatus.overTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="延期原因：">
          <el-input :rows="6" type="textarea" v-model="form.desc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="voteStatus.delayVoteFlag = false">取 消</el-button>
        <el-button type="primary" @click="delayFn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 终止投票 || 提前结束 -->
    <el-dialog
      :title="voteStatus.overTitle"
      :visible.sync="voteStatus.overFlag "
      width="600px"
      center
    >
      <el-form ref="voteForm" :model="voteFormOver" label-width="80px">
        <el-input :rows="6" type="textarea" v-model="voteFormOver.desc"></el-input>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="voteStatus.overFlag = false">取 消</el-button>
        <el-button type="primary" @click="voteStatus.overFlag = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 详情html -->
    <el-dialog :visible.sync="detailEditDia" class="edit-dia-wrapper">
      <div class="ql-container ql-snow">
        <div class="ql-editor">
          <div v-html="setup2EditForm.region">{setup2EditForm.region}}</div>
        </div>
      </div>
    </el-dialog>

    <!-- 单人详情html -->
    <el-dialog title="用户投票详情" center :visible.sync="singleDetail.flag">
      <div class="single-wrapper">
        <div
          class="single-item-wrap"
          v-for="   (item,index) in singleDetail.tableData"
          :key="index"
        >
          <div class="single-title">{{item.title}}</div>
          <ul v-for="(childrenItem,childrenIndex) in item.options" :key="childrenIndex">
            <li
              :class="{ 'singele-active':childrenItem.hasChoose==1 }"
            >{{childrenItem.answerOption}}.{{childrenItem.answerContent}}</li>
          </ul>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { setItem, getItem } from "../../tools/common";
import Editor from "./Editor.vue";
export default {
  data() {
    var titleVerification = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入标题"));
      } else {
        value = value.replace(/\s+/g, "");
        if (value === "") {
          callback(new Error("标题不能为空"));
        }
        callback();
      }
    };
    var ContentVerification = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入内容"));
      } else {
        value = value.replace(/\s+/g, "");
        if (value == "<p></p>") {
          callback(new Error("内容不能为空"));
        }
        callback();
      }
    };
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      setup1Form: {
        area: null,
        selectOption: [
          {
            communityId: 1,
            communityName: ""
          }
        ]
      },
      setup1Rules: {
        area: [
          {
            required: true,
            message: "区域不能为空",
            trigger: "blur"
          }
        ]
      },
      setup2EditForm: {
        title: "",
        starTime: "",
        region: ""
      },
      setup2EditRules: {
        title: [
          { validator: titleVerification, trigger: "blur" },
          { min: 1, max: 25, message: "长度在 1 到 25个字符", trigger: "blur" },
          { required: true, message: "请输入标题", trigger: "blur" }
        ],
        starTime: [
          {
            required: true,
            message: "时间不能为空",
            trigger: "blur"
          }
        ],
        region: [
          { validator: ContentVerification, trigger: "blur" },
          { required: true, message: "请输入内容", trigger: "blur" }
        ]
      },
      fileList: [],
      artList: [],
      dynamicValidateForm: {
        domains: [
          {
            name: "",
            radio: 1,
            selectNum: 1,
            selectFlag: false,
            delItemFlag: false,
            topFlag: true,
            maxNum: 1,
            select: [
              {
                selectZM: "A",
                selectInput: "",
                addFlag: true,
                delFlag: false
              }
            ]
          }
        ]
      },
      // 默认是新增投票。true新增投票false编辑投票
      addVote: {
        status: true,
        voteId: null
      },
      form: {
        isShow: false
      },
      tableFlag: 1,
      setupCount: 0,
      diaFileFlag: false,
      diaArticleFlag: false,
      chooseList: [],
      voteStatus: {
        delayVoteFlag: false,
        overFlag: false,
        overTitle: "",
        overTime: ""
      },
      voteFormDelay: {},
      voteFormOver: { desc: "" },
      tabName: "result",
      resultData: [],
      collapseAct: 0,
      table: {
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        rowCount: 0,
        queryKey: "",
        state: null,
        loading: false
      },
      allVote: {
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        rowCount: 0
      },
      // 详情
      detailActive: 1,
      detailScope: "",
      detailEditDia: false,
      detailState: null,
      resultVoteId: null,
      singleDetail: {
        flag: false,
        tableData: []
      }
    };
  },

  methods: {
    backList() {
      this.detailState = null;
      this.setup1Form.area = null;
      this.setup2EditForm = {
        title: "",
        starTime: "",
        region: ""
      };
      this.chooseList = [];
      this.dynamicValidateForm = {
        domains: [
          {
            name: "",
            radio: 1,
            selectNum: 1,
            selectFlag: false,
            delItemFlag: false,
            topFlag: true,
            maxNum: 1,
            select: [
              {
                selectZM: "A",
                selectInput: "",
                addFlag: true,
                delFlag: false
              }
            ]
          }
        ]
      };
      // 清空表单
      this.tableFlag = 1;
      this.setupCount = 0;
    },
    cleanKey() {
      this.table.currentPage = 1;
      this.table.queryKey = "";
      this.fetchData();
    },
    queryKey() {
      this.table.currentPage = 1;
      this.fetchData();
    },
    currentChangeHandle(currentPage) {
      this.table.currentPage = currentPage;
      this.fetchData();
    },
    voteChange(currentPage) {
      this.allVote.currentPage = currentPage;
      this.fetchAllVote();
    },
    addAnn() {
      this.tableFlag = 2;
      this.addVote.status = true;
      this.addVote.voteId = null;
    },
    goBack() {},
    setBack() {
      if (this.setupCount != 0) {
        this.setupCount--;
      }
    },
    setNext() {
      switch (this.setupCount) {
        case 0:
          this.setupRulesFn("setup1Form");
          break;
        case 1:
          this.setupRulesFn("setup2EditForm");
          break;
        case 2:
          this.setupRulesFn("setup3Form");
          break;
      }
    },
    setupRulesFn(formName) {
      if (formName == "setup3Form") {
        this.setupCount++;
        return;
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.setupCount++;
        }
      });
    },
    saveVoteData(formName) {
      let setup4Arr = this.dynamicValidateForm.domains;
      let flag = true;
      for (let i = 0; i < setup4Arr.length; i++) {
        if (setup4Arr[i].select.length < 2) {
          flag = false;
        }
      }
      if (!flag) {
        this.$message.error({
          message: "选项不得少于2个"
        });
        return;
      }

      this.$refs[formName].validate(vaild => {
        if (vaild) {
          // 发送数据给后台;
          this.httpVoteData();
        }
      });
    },

    // 发送数据给后台
    httpVoteData() {
      let url = "";
      let p = {};
      let info = getItem("info");
      if (this.addVote.status) {
        url = "/vote/add";
        p.communityId = info.communityId;
      } else {
        url = "/vote/modify";
        p.voteId = this.addVote.voteId;
      }
      let _obj = {};
      // 第一步
      _obj.range = 1;
      // 第二步
      _obj.title = this.setup2EditForm.title;
      _obj.startTime = this.setup2EditForm.starTime[0];
      _obj.endTime = this.setup2EditForm.starTime[1];
      _obj.content = this.setup2EditForm.region;
      // 第三步

      if (this.chooseList.length >= 1) {
        _obj.extras = [];
        for (let i = 0; i < this.chooseList.length; i++) {
          let extra = {};
          extra.extraType = this.chooseList[i].extraType;
          if (this.chooseList[i].extraType == 1) {
            extra.detailId = this.chooseList[i].fileId;
          } else {
            extra.detailId = this.chooseList[i].articleId;
          }
          _obj.extras.push(extra);
        }
      }

      _obj.items = [];
      let setup4Arr = this.dynamicValidateForm.domains;

      for (let i = 0; i < setup4Arr.length; i++) {
        let item = {};
        item.title = setup4Arr[i].name;
        item.itemType = setup4Arr[i].radio;
        item.chooseNum = setup4Arr[i].selectNum;
        item.options = [];
        for (let j = 0; j < setup4Arr[i].select.length; j++) {
          let selectItem = {};
          selectItem.answerOption = setup4Arr[i].select[j].selectZM;
          selectItem.answerContent = setup4Arr[i].select[j].selectInput;
          item.options.push(selectItem);
        }
        _obj.items.push(item);
      }
      p.voteJson = JSON.stringify(_obj);
      // 传数据给后台
      this.$http
        .fetch(url, p)
        .then(res => {
          if (res.code == 0) {
            this.$message({
              message: "保存成功",
              type: "success"
            });
            this.fetchData();
            this.tableFlag = 1;
            this.setupCount = 0;
          }
        })
        .catch(err => {});
    },
    inputFn(value) {
      //富文本编辑器
      this.setup2EditForm.region = value;
    },
    onEditorBlur(value) {},
    cRes(item) {
      let itemExtraType;
      let proName = "";
      let itemName = "";
      if (item["fileId"] != undefined) {
        // 文件
        this.diaFileFlag = false;
        itemExtraType = 1;
        proName = "fileId";
        itemName = item.name;
      } else {
        // 文章
        this.diaArticleFlag = false;
        itemExtraType = 2;
        proName = "articleId";
        itemName = item.title;
      }

      let flag = false;
      let fileArr = [];

      if (this.chooseList.length >= 1) {
        for (let i = 0; i < this.chooseList.length; i++) {
          if (this.chooseList[i].extraType == itemExtraType) {
            if (item[proName] == this.chooseList[i][proName]) {
              flag = true;
            }
          }
        }
        if (flag) {
          return;
        }
      }
      let _obj = {};
      (_obj.extraType = itemExtraType), (_obj[proName] = item[proName]);
      _obj.name = itemName;
      this.chooseList.push(_obj);
    },
    setup3Del(_index) {
      let _this = this;
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.chooseList.splice(_index, 1);
        })
        .catch(() => {});
    },
    addSelect() {
      let obj = {
        name: "",
        radio: 1,
        selectNum: 1,
        selectFlag: false,
        delItemFlag: true,
        topFlag: true,
        maxNum: 1,
        select: [
          {
            selectZM: "A",
            selectInput: "",
            addFlag: true
          }
        ]
      };
      this.dynamicValidateForm.domains.push(obj);
    },
    addZM(parentIndex, _index) {
      let _obj = {
        selectZM: null,
        selectInput: "",
        addFlag: true,
        delFlag: true
      };
      let _len = this.dynamicValidateForm.domains[parentIndex].select.length;
      switch (_len) {
        case 0:
          _obj.selectZM = "A";
          _obj.delFlag = false;
        case 1:
          _obj.selectZM = "B";
          break;
        case 2:
          _obj.selectZM = "C";
          break;
        case 3:
          _obj.selectZM = "D";
          _obj.addFlag = false;
          break;
      }
      this.dynamicValidateForm.domains[parentIndex].select[
        _index
      ].addFlag = false;
      this.dynamicValidateForm.domains[parentIndex].select.push(_obj);
      this.dynamicValidateForm.domains[
        parentIndex
      ].maxNum = this.dynamicValidateForm.domains[parentIndex].select.length;
    },
    delZM(parentIndex, _index) {
      this.dynamicValidateForm.domains[parentIndex].select.splice(_index, 1);

      let len = this.dynamicValidateForm.domains[parentIndex].select.length;

      this.dynamicValidateForm.domains[parentIndex].select[
        len - 1
      ].addFlag = true;

      this.dynamicValidateForm.domains[parentIndex].maxNum = len;
      if (this.dynamicValidateForm.domains[parentIndex].selectNum > len) {
        this.dynamicValidateForm.domains[parentIndex].selectNum = len;
      }

      if (len == 2) {
        this.dynamicValidateForm.domains[parentIndex].select[0].selectZM = "A";
        this.dynamicValidateForm.domains[parentIndex].select[1].selectZM = "B";
      } else if (len == 3) {
        this.dynamicValidateForm.domains[parentIndex].select[0].selectZM = "A";
        this.dynamicValidateForm.domains[parentIndex].select[1].selectZM = "B";
        this.dynamicValidateForm.domains[parentIndex].select[2].selectZM = "C";
      }
    },
    delCard(parentIndex) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.dynamicValidateForm.domains.splice(parentIndex, 1);
        })
        .catch(() => {});
    },
    topCard(parentIndex) {
      this.dynamicValidateForm.domains[parentIndex].topFlag = false;
    },
    botCard(parentIndex) {
      this.dynamicValidateForm.domains[parentIndex].topFlag = true;
    },

    delayFn() {
      this.voteStatus.delayVoteFlag = false;
    },
    tabClick(tab, event) {
      if (tab.name == "allVote") {
        this.fetchAllVote();
      } else if (tab.name == "result") {
        this.resultVote();
      }
    },
    collapseFn() {},
    selectChange() {
      this.table.currentPage = 1;
      this.fetchData();
    },

    fetchData() {
      let url = "/vote/list";
      let info = getItem("info") ? getItem("info") : {};
      let stateNum;
      let p = {
        communityId: info.communityId,
        start: (this.table.currentPage - 1) * this.table.pageSize,
        num: this.table.pageSize,
        title: this.table.queryKey
      };

      switch (this.table.state) {
        case "0":
          p.state = 0;
          break;
        case "1":
          p.state = 1;
          break;
        case "2":
          p.state = 2;
          break;
        case "3":
          p.state = 3;
          break;
        case "4":
          p.state = 4;
          break;
        case "5":
          p.state = 5;
          break;
      }
      this.table.loading = true;
      this.$http
        .fetch(url, p)
        .then(res => {
          this.table.tableData = res.data.rows;
          this.table.rowCount = res.data.total;
          this.table.loading = false;
        })
        .catch(err => {
          this.table.loading = false;
        });
    },
    setup3FetchFile() {
      this.diaFileFlag = true;
      let url = "/file/list";
      let info = getItem("info");
      let p = {
        communityId: info.communityId,
        start: 0,
        num: 1000
      };
      this.$http
        .fetch(url, p)
        .then(res => {
          this.fileList = res.data.rows;
        })
        .catch(err => {});
    },
    setup3FetchArt() {
      this.diaArticleFlag = true;
      let url = "/article/list";
      let info = getItem("info");
      let p = {
        communityId: info.communityId,
        start: 0,
        num: 1000
      };
      this.$http
        .fetch(url, p)
        .then(res => {
          this.artList = res.data.rows;
        })
        .catch(err => {});
    },

    editStatus(_scope, _type) {
      let url = "";
      let message = "";
      let confirmMes = "";
      switch (_type) {
        case 1:
          url = "/vote/publish";
          message = "发布成功";
          confirmMes = "发布";
          break;
        case 2:
          url = "/vote/unpublish";
          message = "取消成功";
          confirmMes = "取消发布";

          break;
        case 3:
          url = "/vote/stop";
          message = "终止成功";
          confirmMes = "终止";

          break;
        case 4:
          url = "/vote/delete";
          message = "删除成功";
          break;
      }

      this.$confirm(`是否确认${confirmMes}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 1发布 2取消 3终止 4删除
          let p = {};
          p.voteId = _scope.voteId;

          this.$http
            .fetch(url, p)
            .then(res => {
              this.$message({
                type: "success",
                message: message
              });
              this.fetchData();
            })
            .catch(err => {});
        })
        .catch(() => {});
    },
    del(_scope) {
      let url = "/vote/delete";
      let p = {};
      p.voteId = _scope.voteId;
      this.$confirm("是否确认删除", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http
            .fetch(url, p)
            .then(res => {
              this.$message({
                type: "success",
                message: "删除成功"
              });
              this.fetchData();
            })
            .catch(err => {});
        })
        .catch(action => {});
    },
    edit(_scope, _type) {
      this.addVote.status = false;
      this.addVote.voteId = _scope.voteId;
      let voteId = _scope.voteId;
      let url = "/vote/detail";
      let p = {
        voteId: voteId
      };
      let info = getItem("info");
      this.$http
        .fetch(url, p)
        .then(res => {
          let data = res.data;
          // 第一步
          this.setup1Form.area = data.voteRange;
          this.setup1Form.selectOption = [
            {
              communityId: 1,
              communityName: info.communityName
            }
          ];
          if (_type) {
            this.detailState = data.state;
            for (let i = 0; i < this.setup1Form.selectOption.length; i++) {
              if (
                this.setup1Form.area ==
                this.setup1Form.selectOption[i].communityId
              ) {
                this.detailScope = this.setup1Form.selectOption[
                  i
                ].communityName;
              }
            }
          }

          // 第二步
          this.setup2EditForm.title = data.title;
          this.setup2EditForm.starTime = [data.startTime, data.endTime];
          this.setup2EditForm.region = data.content;
          this.chooseList = [];
          // 第三步
          if (data.extras.length >= 1) {
            for (let i = 0; i < data.extras.length; i++) {
              let extra = {};
              extra.extraType = data.extras[i].extraType;
              extra.name = data.extras[i].name;
              if (data.extras[i].extraType == 1) {
                extra.fileId = data.extras[i].detailId;
              } else {
                extra.articleId = data.extras[i].detailId;
              }
              this.chooseList.push(extra);
            }
          }

          // 第四步
          this.dynamicValidateForm = {
            domains: []
          };
          for (let i = 0; i < data.items.length; i++) {
            let item = {};
            item.name = data.items[i].title;
            item.radio = data.items[i].itemType;
            item.selectNum = data.items[i].chooseNum;
            if (data.items[i].itemType == 1) {
              item.selectFlag = false;
            } else {
              item.selectFlag = true;
            }
            if (i == 0) {
              item.delItemFlag = false;
            } else {
              item.delItemFlag = true;
            }
            item.topFlag = true;
            item.maxNum = data.items[i].orderNum;
            item.select = [];
            for (let j = 0; j < data.items[i].options.length; j++) {
              let optionItem = {};
              optionItem.selectZM = data.items[i].options[j].answerOption;
              optionItem.selectInput = data.items[i].options[j].answerContent;
              item.select.push(optionItem);
            }
            if (item.select.length == 1) {
              item.select[0].addFlag = true;
              item.select[0].delFlag = false;
            } else if (item.select.length == 2) {
              item.select[0].addFlag = false;
              item.select[0].delFlag = false;
              item.select[1].addFlag = true;
              item.select[1].delFlag = true;
            } else if (item.select.length == 3) {
              item.select[0].addFlag = false;
              item.select[0].delFlag = false;
              item.select[1].addFlag = false;
              item.select[1].delFlag = true;
              item.select[2].addFlag = true;
              item.select[2].delFlag = true;
            } else if (item.select.length == 4) {
              item.select[0].addFlag = false;
              item.select[0].delFlag = false;
              item.select[1].addFlag = false;
              item.select[1].delFlag = true;
              item.select[2].addFlag = false;
              item.select[2].delFlag = true;
              item.select[3].addFlag = false;
              item.select[3].delFlag = true;
            }
            this.dynamicValidateForm.domains.push(item);
          }
          if (_type) {
            // 是详情的
            this.tableFlag = 4;
          } else {
            // 修改的
            this.tableFlag = 2;
            this.setupCount = 0;
          }
        })
        .catch(err => {});
    },
    // 详情
    viewDetail(_scope) {
      console.log(`_scope`, _scope);
      this.resultVoteId = _scope.voteId;
      this.edit(_scope, 1);
    },
    detailCollapse() {},
    detailRegion() {
      this.detailEditDia = true;
    },
    statistics() {
      this.tableFlag = 3;
      this.tabName = "result";
      this.resultVote();
    },
    // 结果统计
    resultVote() {
      let url = "/vote/resultDetail";
      let p = {};
      p.voteId = this.resultVoteId;
      this.$http
        .fetch(url, p)
        .then(res => {
          this.resultData = res.data;
        })
        .catch(err => {});
    },
    // 全部投票
    fetchAllVote() {
      let _this = this;
      let url = "/vote/memberDetail";
      let p = {
        voteId: _this.resultVoteId,
        start: (_this.allVote.currentPage - 1) * _this.allVote.pageSize,
        num: _this.allVote.pageSize
      };
      console.log(`p`, p);
      this.$http
        .fetch(url, p)
        .then(res => {
          console.log(`res`, res);
          this.allVote.tableData = res.data.rows;
          this.allVote.rowCount = res.data.total;
        })
        .catch(err => {});
    },
    singleDetailFn(_scope) {
      console.log(`_scope`, _scope);
      let url = "/vote/memberVoteDetail";
      let p = {};
      p.voteId = this.resultVoteId;
      p.userId = _scope.userId;
      this.$http
        .fetch(url, p)
        .then(res => {
          console.log(res);
          this.singleDetail.flag = true;
          this.singleDetail.tableData = res.data;
        })
        .catch(err => {});
    }
  },
  components: {
    editor: Editor
  },
  watch: {
    dynamicValidateForm: {
      //深度监听，可监听到对象、数组的变化
      handler(val, oldVal) {},
      deep: true
    }
  },
  mounted() {
    this.fetchData();
    let info = getItem("info") ? getItem("info") : {};
    this.setup1Form.selectOption[0].communityName = info.communityName;
    this.setup1Form.selectOption[0].communityId = 1;
  }
};
</script>
<style scoped>
.setup-wrapper {
  margin-top: 20px;
}
.setup-wrapper >>> .el-form-item {
  display: flex;
  justify-content: center;
}
.set-1-form {
  /* border: 1px solid red; */
  /* height: 358px; */
  height: 100%;
  display: flex;
  flex-direction: column;
  align-content: space-around;
}
.setup-1-btn-wrap {
  text-align: center;
  -webkit-box-flex: 1;
  -ms-flex: 1 0 auto;
  flex: 1 0 auto;
  justify-content: center;
  align-items: flex-end;
  display: flex;
}
.vote {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.el-breadcrumb {
  flex: 0 0 auto;
}
.section-content {
  flex: 1 0 auto;
}
.content-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.setup-top {
  flex: 0 0 auto;
}
.set-1 {
  flex: 1 0 auto;
  margin-top: 30px;
}
.setup-1-btn-wrap >>> .el-form-item__content {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}
.setup-wrapper-2 >>> .el-form-item__content {
  width: 750px;
  text-align: left;
}
.ql-snow {
  text-align: left !important;
}
.setup-wrapper-3 {
  text-align: center;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}
.item:hover {
  cursor: pointer;
  color: #409eff;
}
.box-card {
  width: 480px;
}
.file-dia >>> .el-dialog {
  min-width: 622px;
}
.list-data-wrap {
  margin-top: 30px;
}
.list-item {
  background-color: #ccc;
  margin-bottom: 15px;
  line-height: 30px;
  width: 400px;
  text-align: left;
  padding: 0 10px;
}
.choose-item-wrap {
  display: flex;
  justify-content: center;
}
.item-del {
  line-height: 30px;
  color: #0099ff;
  margin-left: 6px;
}
.item-del:hover {
  cursor: pointer;
}

.set4-icon {
  float: right;
  padding: 3px 0;
  /* color: #0099ff; */
  margin-right: 6px;
}
.set4-icon:hover {
  cursor: pointer;
}
.select-wrap .max-num-input {
  width: 120px;
  margin-left: 30px;
}
.select-desc {
  display: flex;
  margin-bottom: 20px;
}
.box-card {
  width: 580px;
}
.content-input {
  width: 300px;
}
.edit-btn-wrap {
  color: #0099ff;
  margin-left: 20px;
}
.edit-btn-wrap span:hover {
  cursor: pointer;
}
.edit-btn-wrap span:first-of-type {
  margin-right: 10px;
}
.box-card-form {
  margin-bottom: 60px;
}
.icon-add {
  display: inline-block;
  margin: 0 auto;
  border: 1px solid #000;
  text-align: center;
  font-size: 30px;
  margin-bottom: 30px;
  border-radius: 50%;
}
.icon-add:hover {
  cursor: pointer;
}
.icon-wrap {
  text-align: center;
}
.setup4-box-card-wrap >>> .el-card__body {
  padding: 0;
}
.card-from {
  padding: 20px;
}
.setup-4-wrap {
  width: 600px;
  background-color: rgba(44, 94, 163, 0.0470588235294118);
  margin: 0 auto;
  text-align: center;
  padding: 20px;
}
.img-wrap p {
  font-size: 14px;
  margin-top: 10px;
}
.img-wrap img {
  width: 40px;
  height: 40px;
}
.setup-4-desc {
  padding: 20px;
  text-align: left;
}
.setup-4-desc h6 {
  font-weight: bold;
}
.setup-4-desc ul {
  margin-top: 10px;
}
.desc-li {
  margin-top: 10px;
}
.edi-wrapper {
  align-items: flex-start;
}
.vote-card-wrap {
  display: flex;
  justify-content: space-between;
}
.card-item-time {
  margin-right: 10px;
}
.card-item-name {
  max-width: 346px;
}
.rule-span {
  color: #f56c6c;
  margin-right: 10px;
}
.set4-wrap {
  padding: 20px;
}
.detail-section {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.detail-collapse {
  flex: 0 0 auto;
}
.detail-btn-wrapper {
  flex: 1 0 auto;
  justify-content: center;
  align-items: flex-end;
  display: flex;
  margin-top: 30px;
}
.edit-dia-wrapper >>> .el-dialog {
  min-width: 980px;
}
.edit-dia-wrapper .ql-container.ql-snow {
  border: none;
}
.view-region {
  color: #409eff;
}
.view-region:hover {
  cursor: pointer;
}
.detail-select-li {
  display: flex;
}
.detail-collapse >>> .el-collapse-item__header,
.result-wrapper >>> .el-collapse-item__header {
  font-weight: bold;
  font-size: 15px;
}

.select-item-li {
  margin-bottom: 16px;
  font-size: 14px;
}
.file-wrap,
.info-detail,
.scope-detail {
  font-size: 14px;
}
.single-wrapper .single-item-wrap {
  display: flex;
  flex-direction: column;
  justify-content: center;
  /* align-items: center; */
}
.single-title {
  margin-right: 20px;
}
.single-item-wrap {
  margin-bottom: 40px;
  font-size: 16px;
}
.single-item-wrap ul {
  display: flex;
  margin-top: 10px;
}
.single-item-wrap li {
  margin-right: 30px;
}
.single-item-wrap li.active {
  color: red;
}
.single-item-wrap .singele-active {
  color: red;
}
</style>


